package swu.user;

import swu.commodity.CommodityRepo;
import swu.core.ObjectRepo;
import swu.core.ResultSetIterator;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserRepo extends ObjectRepo
{
    CommodityRepo commodityRepo;

    public void addUser(User user) throws SQLException
    {
        String temp = "insert into users(name,password) values('%s','%s')";
        String sql = String.format(temp,user.getName(),user.getPassword());
        this.executeSQL(sql);
    }

    public Boolean isUserExists(User user) throws SQLException
    {
        List<User> users = new ArrayList<>();

        String temp = "select * from users where name='%s'";
        String sql = String.format(temp,user.getName());

        this.queryAll(sql, new ResultSetIterator()
        {
            @Override
            public void visit(ResultSet rs) throws SQLException
            {
                users.add(getOneUser(rs));
            }
        });

        return (!users.isEmpty());
    }

    public User getOneUser(ResultSet resultSet) throws SQLException
    {
        User user = new User();

        user.setName(resultSet.getString("name"));
        user.setPassword(resultSet.getString("password"));

        return user;
    }

    public List<User> getAllUsers() throws SQLException
    {
        List<User> users = new ArrayList<>();
        String sql = "select * from users";

        this.queryAll(sql, new ResultSetIterator() {
            @Override
            public void visit(ResultSet rs) throws SQLException
            {
                users.add(getOneUser(rs));
            }
        });

        return users;
    }

    public void createCart(User user) throws SQLException
    {
        String sql = "create table " + user.getName() + "_cart like commodities";

        this.executeSQL(sql);
    }
}
